<?php
class empire extends spController{
	
	private $appkeys;
	
	function __construct(){
		parent::__construct();
		$this -> appkeys = unserialize(spAccess('r','appkeys'));
	}
	
	function index(){
		$this->send_order();
		$this->send_refund();
	}
	
	function send_order(){
		$orders = spClass('m_order') -> getOrders('0');
		foreach ($orders as $order){
			$p = array('action'=>'create','oid'=>$order['oid'],'alipay_no'=>$order['alipay_no'],'title'=>$this->url_encode($order['title']));
			$result = file_get_contents(EMPIRE_URL.'/e/tool/toporder/index.php?'.$this->parse_combine($p).'&sign='.$this->parse_md5_encode($p, SKEY));
			if($result > 0){
				$session = spClass('m_top') -> getSessions($order['topsession_id']);
				$top_deal = $this -> top_order_done($order['tid'], $session[0]['sessionkey'],$session[0]['appkey']);
				if($top_deal == true){
					spClass('m_order') -> doneOrder($order['oid']);
				}
			}
			else{
				spClass('m_order') -> errorOrder($order['oid'],$result);
			}
		}
	}
	
	function send_refund(){
		$orders = spClass('m_order') -> getOrders('-1');
		foreach ($orders as $order){
			$p = array('action'=>'delete','oid'=>$order['oid']);
			$result = file_get_contents(EMPIRE_URL.'/e/tool/toporder/index.php?'.$this->parse_combine($p).'&sign='.$this->parse_md5_encode($p, SKEY));
			if($result > 0){
				spClass('m_order') -> errorOrder($order['oid'],'-2');
			}
		}
	}
	
	private function top_order_done($tid,$sessionkey,$appkey){
		import('./TopSdk.php');
		$c = new TopClient;
		$c->appkey = $appkey;
		$c->secretKey = $this -> appkeys[$appkey];
		$req = new LogisticsDummySendRequest;
		$req->setTid($tid);
		$resp = $c->execute($req, $sessionkey);
		return $resp -> shipping -> is_success;
	}
	
	private function parse_md5_encode($array,$SKEY){
		ksort($array);//将数组排序
		$string = '';
		foreach ($array as $k => $v){
			$string = $string.$k.$v;
		}
		$string = strtoupper($SKEY.$string.$SKEY);
		$string = mb_convert_encoding($string,"utf-8", "HTML-ENTITIES");
		return md5($string);
	}
	
	private function parse_md5_verify($array,$SKEY,$sign){
		$shouldbe = $this-> parse_md5_encode($array, $SKEY);
		if($shouldbe == $sign){return TRUE;}
		else{return FALSE;}
	}
	
	private function parse_combine($array){
		ksort($array);
		$string = '';
		foreach ($array as $k => $v){
			$string = $string.$k.'='.$v.'&';
		}
		return $string;
	}
	
	private function url_encode($str){
		return str_replace('+', '!', base64_encode($str));
	}
	
	private function url_decode($str){
		return base64_decode(str_replace('!', '+', $str));
	}
}